<template>
  <div class="todoapp">
    <TodoHeader @getname="addList" :arr="list"></TodoHeader>
    <TodoMain :arr="showArr" @del="delFn"></TodoMain>
    <TodoFooter
      :arr="showArr"
      @changeType="changeFn"
      @clearType="clearFn"
    ></TodoFooter>
  </div>
</template>

<script>
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";
export default {
  data() {
    return {
      cons: "all", // 要显示的数据类型字符串
      list: JSON.parse(localStorage.getItem("todolist")) || [],
    };
  },
  methods: {
    addList(thename) {
      this.list.push({
        id:
          this.list.length === 0 ? 100 : this.list[this.list.length - 1].id + 1,
        name: thename,
        isDone: false,
      });
    },
    delFn(index) {
      this.list.splice(index, 1);
    },
    changeFn(conStr) {
      // 类型字符串
      this.cons = conStr; // cons中转作用, 为了让TodoFooter的标记字符串值, 可以在计算属性中使用
    },
    clearFn() {
      // 清空已完成
      this.list = this.list.filter((obj) => obj.isDone === false); // 筛选未完成的覆盖给list任务
    },
  },
  computed: {
    showArr() {
      // 计算属性里根据TodoFooter传出的字符, 决定过滤出什么数据传给TodoMain显示
      // conStr的值从list里筛选出来
      if (this.cons === "ok") {
        // 返回已完成
        return this.list.filter((obj) => obj.isDone === true);
      } else if (this.cons === "no") {
        // 返回未完成
        return this.list.filter((obj) => obj.isDone === false);
      } else {
        // 返回全部
        return this.list;
      }
    },
  },
  watch: {
    list: {
      handler(newVal) {
        console.log(newVal);
        localStorage.setItem("todolist", JSON.stringify(newVal));
      },
      deep: true, // 数组里对象的属性改变也要被监听.. (完成: 勾选v, 也能同步到本地...)
    },
  },
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
};
</script>

<style>
</style>